package b2.widget.fight
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.fight.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.warehouse.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.text.*;
	import flash.utils.Timer;
	
	import org.flixel.*;

	public class BattleEndPane extends Sprite
	{
		//倒计时时长
		private const COUND_DOWN:int = 8;
		//当前关
		private var battleOrder:int;
		//战役的索引
		private var campIndex:int;
		//战斗胜利方
		private var winSide:int;
		//倒计时（秒)
		private var countdown:int;
		//计时器
		private var timer:Timer;
		//倒计时显示信息
		private var countDownText:TextField;
		
		public function BattleEndPane(campIndex:int, battleOrder:int, winSide:int, evaluation:int)
		{
			super();
			this.campIndex = campIndex;
			this.battleOrder = battleOrder;
			this.winSide = winSide;
			var state:PlayState = FlxG.state as PlayState;
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			//透明背景
			var bgr:Sprite = new Sprite();
			var gfx:Graphics = bgr.graphics;
			gfx.beginFill(0x000000, 0.01);
			gfx.drawRect(0, 0, BFont.stageWidth, BFont.stageHeight);
			gfx.endFill();
			addChild(bgr);
			//背景水纹
			var enemies:Array = campConfig.getEnemy();
			var enemyConfig:EnemyConfig = Config.enemyConfigs[enemies[0][0]];
			var tankConfig:TankConfig = Config.objectConfigs[enemyConfig.tankIndex];
			var Bgr:Class = ResourceHelper.getInstance().getClassByName(tankConfig.iconImage);
			var enemyBgr:Sprite = new Bgr();
			enemyBgr.filters = [new ColorMatrixFilter(BFont.blackWhiteFilter)];
			enemyBgr.x = 340;
			enemyBgr.y = 150;
			enemyBgr.width = 300;
			enemyBgr.height = 300;
			enemyBgr.alpha = 0.5;
			addChild(enemyBgr);
			//背景图片
			var EndPaneBgr:Class = ResourceHelper.getInstance().getClassByName("EndPaneBgr");
			var endPaneBgr:Sprite = new EndPaneBgr();
			endPaneBgr.x = (this.width - endPaneBgr.width) / 2;
			endPaneBgr.y = (this.height - endPaneBgr.height) / 2;
			addChild(endPaneBgr);
			//关卡胜利或者失败
			var endMsgText:TextField = new TextField();
			endMsgText.selectable = false;
        	endMsgText.autoSize = TextFieldAutoSize.LEFT;
			endMsgText.defaultTextFormat = new TextFormat("微软雅黑", 20, 0xFFFF00);
			endMsgText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			if (state.mySide == winSide)
				endMsgText.text = "第 " + (battleOrder + 1).toString() + " 关完成";
			else
				endMsgText.text = "第 " + (battleOrder + 1).toString() + " 关失败";
			endMsgText.x = 20;
			endMsgText.y = 25;
			endPaneBgr.addChild(endMsgText);
			//玩家昵称
			var playerNameText:TextField = new TextField();
			playerNameText.selectable = false;
        	playerNameText.autoSize = TextFieldAutoSize.CENTER;
			playerNameText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0xFFFF00);
			playerNameText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			playerNameText.text = "玩家昵称";
			playerNameText.x = 190;
			playerNameText.y = 76;
			endPaneBgr.addChild(playerNameText);
			//战利品
			var awardText:TextField = new TextField();
			awardText.selectable = false;
        	awardText.autoSize = TextFieldAutoSize.CENTER;
			awardText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0xFFFF00);
			awardText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			awardText.text = "奖励";
			awardText.x = 360;
			awardText.y = 76;
			endPaneBgr.addChild(awardText);
			//评价等级
			var evaluationText:TextField = new TextField();
			evaluationText.selectable = false;
        	evaluationText.autoSize = TextFieldAutoSize.CENTER;
			evaluationText.defaultTextFormat = new TextFormat("微软雅黑", 80, 0x4040FF, true, true);
			var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
			gradientGlow.distance = 0;
			gradientGlow.angle = 45;
			gradientGlow.colors = [0xFFFFFF, 0xFFFFFF];
			gradientGlow.alphas = [0, 1];
			gradientGlow.ratios = [0, 255];
			gradientGlow.blurX = 40;
			gradientGlow.blurY = 40;
			gradientGlow.strength = 2.5;
			gradientGlow.quality = BitmapFilterQuality.HIGH;
			gradientGlow.type = BitmapFilterType.OUTER;
			evaluationText.filters = [gradientGlow];
			//比赛战役
			if (campConfig.type == 1)
			{
				if (winSide == TankSprite.SIDE_DRAW)
				{
					evaluationText.text = " 平 ";
				}
				else if (state.mySide == winSide)
				{
					evaluationText.text = " 胜 ";
				}
				else
				{
					evaluationText.text = " 败 ";
				}
			}
			//普通战役
			else
			{
				//胜利
				if (state.mySide == winSide)
					evaluationText.text = " " + Config.basicConfig.standardName[evaluation] + " ";
				else
					evaluationText.text = " 败 ";
			}
			evaluationText.x = 80 - evaluationText.width / 2;
			evaluationText.y = 85;
			endPaneBgr.addChild(evaluationText);
			//奖励
			var playerSlots:Object = FightScene.getInstance().leftPane.playerSlots;
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			var playerSlot:PlayerSlot = playerSlots[me.campTankId];
			var awardSprite:Sprite = getAwardSprite(playerSlot.playerName, FightScene.getInstance().awardList[me.campTankId]);
			awardSprite.x = 170;
			awardSprite.y = 106;
			endPaneBgr.addChild(awardSprite);
			var count:int = 1;
			for (var tankId:String in playerSlots)
			{
				if (parseInt(tankId) != me.campTankId)
				{
					playerSlot = playerSlots[tankId];
					awardSprite = getAwardSprite(playerSlot.playerName, FightScene.getInstance().awardList[tankId]);
					awardSprite.x = 170;
					awardSprite.y = 106 + count * 58;
					endPaneBgr.addChild(awardSprite);
					if (count++ >= 2)
						break;
				}
			}
			//倒计时信息
			countDownText = new TextField();
			countDownText.selectable = false;
        	countDownText.autoSize = TextFieldAutoSize.LEFT;
			countDownText.defaultTextFormat = new TextFormat("微软雅黑", 18, 0xFFFFFF);
			countDownText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			countDownText.x = 20;
			countDownText.y = 298;
			endPaneBgr.addChild(countDownText);
			//动作按钮（立即下一关或者立即退出）
			var ButtonBgr:Class = ResourceHelper.getInstance().getClassByName("ButtonBgr0");
			var actionButton:BasicButton = new BasicButton(ButtonBgr, "立即继续");
			actionButton.x = 400;
			actionButton.y = 300;
			endPaneBgr.addChild(actionButton);
			//任务胜利
			if (state.mySide == winSide)
			{
				//还有下一关
				if (battleOrder < campConfig.battleIndex.length - 1)
				{
					actionButton.text = "立即继续";
					actionButton.addEventListener(MouseEvent.CLICK, onButtonNextClick);
				}
				else
				{
					//分享按钮
					var buttonShare:BasicButton = new BasicButton(ButtonBgr, "分享");
					buttonShare.x = 300;
					buttonShare.y = 300;
					buttonShare.addEventListener(MouseEvent.CLICK, onButtonShareClick);
					endPaneBgr.addChild(buttonShare);
					//如果是英雄模式
					if (state.isHeroMode)
					{					
						var name:String = PlayerInfoManager.getInstance().me.name;
						SmartFoxHelper.getInstance().sendPublicMessage("<a href ='event:login'><font color='#0000FF'>" + name + 
							"</font></a>在英雄模式下闯过了<font color='#0000FF'>" + campConfig.name + "</font>");
					}
					actionButton.text = "立即退出";
					actionButton.addEventListener(MouseEvent.CLICK, onButtonQuitClick);
				}
			}
			else
			{
				actionButton.text = "立即退出";
				actionButton.addEventListener(MouseEvent.CLICK, onButtonQuitClick);
			}
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			countdown = COUND_DOWN;
		}
		
		private function onAddedToStage(event:Event):void
		{
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, onTick);
			timer.start();
		}

		private function onRemovedFromStage(event:Event):void
		{
        	if (timer != null)
        	{
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER, onTick);
				timer = null;
        	}
		}
		
		//清理战场物品
		private function getAwardSprite(playerName:String, award:Object):Sprite
		{
			var awardSprite:Sprite = new Sprite();
			var playerText:TextField = new TextField();
			playerText.selectable = false;
        	playerText.autoSize = TextFieldAutoSize.CENTER;
			playerText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0xFFFFFF);
			playerText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			playerText.text = playerName;
			playerText.y = 10;
			awardSprite.addChild(playerText);
			if (award != null)
			{
				var count:int = 0;
				for (var comIndex:String in award)
				{
					var comIndexArr:Array = comIndex.split("_");
					var objectIndex:int = comIndexArr[0];
					var basicLevel:int = comIndexArr[1];
					var strengthenLevel:int = comIndexArr[2];
					var objectItem:ObjectItem = new ObjectItem(objectIndex, basicLevel, strengthenLevel, 0, award[comIndex]);
					objectItem.x = 120 + 60 * count;
					awardSprite.addChild(objectItem);
					count++;
				}
			}
			return awardSprite;
		}
		
		private function onTick(event:TimerEvent):void
		{
        	if (this.parent == null)
        		return;
			var state:PlayState = FlxG.state as PlayState;
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			if (--countdown > 0)
			{
				//任务胜利
				if (state.mySide == winSide)
				{
					//还有下一关
					if (battleOrder < campConfig.battleIndex.length - 1)
						countDownText.text = countdown + "秒后自动下一关";
					else
						countDownText.text = countdown + "秒后退出";
				}
				//任务失败
				else
				{
					countDownText.text = countdown + "秒后退出";
				}
			}
			else
			{
				//任务胜利
				if (state.mySide == winSide)
				{
					//还有下一关
					if (battleOrder < campConfig.battleIndex.length - 1)
						startNextBattle();
					else
						quitBattle();
				}
				//任务失败
				else
				{
					quitBattle();
				}
			}
		}
		
		//点击分享
		private function onButtonShareClick(event:MouseEvent):void
		{
			RRApiHelper.sendFeed("正在坦克要塞开坦克~");
			quitBattle();
		}
		
		private function onButtonQuitClick(event:MouseEvent):void
		{
			quitBattle();
		}
		
		private function onButtonNextClick(event:MouseEvent):void
		{
			startNextBattle();
		}
		
		private function startNextBattle():void
		{
			//关闭自己
			close();
			//开始下一关
			var nextBattle:int = battleOrder + 1;
			var isHeroMode:Boolean = (FlxG.state as PlayState).isHeroMode;
			//单人游戏
			if (SmartFoxHelper.getInstance().isSinglePlayer)
				FightScene.getInstance().startBattleByOrder(nextBattle, isHeroMode);
			//联网游戏
			else
				SmartFoxHelper.getInstance().sendEchoRequest(SmartFoxHelper.BATTLE_START, {"battleOrder": nextBattle, "isHeroMode": isHeroMode});
		}
		
		//退出战役
		private function quitBattle():void
		{
			//关闭自己
			close();
			//保存战斗结果
			saveFightResult();
			//退出战役
			FightScene.getInstance().quit();
		}
		
		//保存战斗结果
		private function saveFightResult():void
		{
			//更新客户端状态
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var state:PlayState = FlxG.state as PlayState;
			var goalFlag:int = state.mySide == winSide || winSide == TankSprite.SIDE_DRAW ? 1 : -1;
			var award:Object = FightScene.getInstance().awardList[me.campTankId];
			//结算荣誉勋章
			if (award != null)
				award[CommonObjConfig.HONOUR_MEDAL + "_0_0"] = award[CommonObjConfig.HONOUR + "_0_0"];  
			//任务胜利（本地更新）
			if (goalFlag > 0)
			{
				if (me.campPackage.campList[campIndex] == null)
					me.campPackage.campList[campIndex] = 1;
				else
					me.campPackage.campList[campIndex]++;
			}
			//在比赛中则更新当前成绩
			if (me.signUpMatchFlag)
			{
				//胜
				if (state.mySide == winSide)
				{
					me.matchHonour += 3;
				}
				//平
				else if (winSide == TankSprite.SIDE_DRAW)
				{
					me.matchHonour += 1;
				}
				//败
				else
				{
					//不加分
				}
			}
			//本地更新
			for (var comIndex:String in award)
			{
				if (me.objPackage.objectList[comIndex] == null)
					me.objPackage.objectList[comIndex] = award[comIndex];
				else
					me.objPackage.objectList[comIndex] += award[comIndex];
			}
			//同步服务器
			ServerHelper.getInstance().endFight(campIndex, goalFlag, FightScene.getInstance().generateMyAwardBalance());
		}
		
		public function close():void
        {
        	if (this.parent != null)
        	{
        		this.parent.removeChild(this);
        	}
        }
        
	}
}